package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.SysUserCompanyRel;
import org.jeecg.modules.system.mapper.SysUserCompanyRelMapper;
import org.jeecg.modules.system.service.ISysUserCompanyRelService;
import org.jeecg.modules.system.vo.SysUserCompanyVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: sys_user_company_rel
 * @Author: jeecg-boot
 * @Date:   2023-08-30
 * @Version: V1.0
 */
@Service
public class SysUserCompanyRelServiceImpl extends ServiceImpl<SysUserCompanyRelMapper, SysUserCompanyRel> implements ISysUserCompanyRelService {

    @Override
    public String queryCompanyNameByCompanyCode(String companyCode) {
        return baseMapper.queryCompanyNameByCompanyCode(companyCode);
    }

    @Override
    public List<SysUserCompanyRel> pageList(SysUserCompanyRel sysUserCompanyRel) {
        baseMapper.pageList(sysUserCompanyRel);
        return baseMapper.pageList(sysUserCompanyRel);
    }

    @Transactional
    @Override
    public Result saveCompany(SysUserCompanyVo sysUserCompanyVo) {
        LambdaQueryWrapper<SysUserCompanyRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserCompanyRel::getObjId,sysUserCompanyVo.getUserId());
        queryWrapper.eq(SysUserCompanyRel::getRelType,0);
        this.remove(queryWrapper);
        List<SysUserCompanyRel> sysUserCompanyRelList = new ArrayList<>();
        SysUserCompanyRel userCompanyRel = null;
        for (String companyCoe : sysUserCompanyVo.getCompanyCodeList()) {
            userCompanyRel = new SysUserCompanyRel();
            userCompanyRel.setObjId(sysUserCompanyVo.getUserId());
            userCompanyRel.setCompanyCode(companyCoe);
            userCompanyRel.setRelType(0);
            sysUserCompanyRelList.add(userCompanyRel);
        }
        this.saveBatch(sysUserCompanyRelList);
        return Result.ok("分配成功！");
    }
}
